/**
 * 初始化创建数据表的SQL语句
 *
 */
export class CrateTable {

	/**
	 * 根据实体类初始化出创创建表的SQL语句
	 * @param entityClass 实体类
	 */
	public static generateCreateTableSQL(entityClass : Function) : string {
		let createTableSQL = `CREATE TABLE IF NOT EXISTS ${entityClass.name.toLowerCase()} (`;
		const properties = Reflect.ownKeys(entityClass.prototype);
		let columns : string[] = [];

		for (const property of properties) {
			if (property === 'constructor') continue; // 跳过构造函数
			const propertyDescriptor = Reflect.getOwnPropertyDescriptor(entityClass.prototype, property);
			const propertyType = propertyDescriptor?.value;
			for (let key in propertyType) {
				let columnInfo = propertyType[key];
				let columnDefinition = '';
				if (columnInfo.hasOwnProperty('field')) {
					let fieldObj = columnInfo['field'];
					columnDefinition = `${fieldObj['field']} ${fieldObj['type'].toUpperCase()}`;
					if (fieldObj.hasOwnProperty('length')) {
						columnDefinition += `(${fieldObj['length']})`;
					}
				} else {
					columnDefinition = `${key} INT`;
				}
				if (columnInfo.hasOwnProperty('notNull') && columnInfo['notNull']) {
					columnDefinition += ' NOT NULL';
				}
				if (columnInfo.hasOwnProperty('primaryKey') && columnInfo['primaryKey']) {
					columnDefinition += ' PRIMARY KEY AUTOINCREMENT';
				}
				columns.push(columnDefinition);
			}
		}

		createTableSQL += columns.join(', ');
		createTableSQL += ')';
		return createTableSQL;
	}
}